#!/bin/bash
# created by wenxzhen @ 2016/9/2

function docker_installed()
{
	echo "checking docker installation..."
	version=`docker --version 1>/dev/null 2>&1`
	
	if [ ! -n "$version" ]; then
		return 0
	else
		return 1
	fi
}

function docker_running()
{
	service_status=`service docker status`
	
	if [[ $service_status =~ "^docker* is running$" ]]; then
		return 1
	else
		return 0
	fi
}

function install_docker()
{
	echo "Trying to install Docker..."
	sudo yum update
	
	# run the docker installation script
	curl -fsSL https://get.docker.com/ | sh
}

function start_docker()
{
	sudo service docker start
}

function install_grafana()
{
	# refer to: https://hub.docker.com/r/monitoringartist/grafana-xxl/
	docker pull monitoringartist/grafana-xxl
}

function run_grafana()
{
	# refer to: https://hub.docker.com/r/monitoringartist/grafana-xxl/
	
	# create /var/lib/grafana as persistent volume storage
	docker run -d -v /var/lib/grafana --name grafana-xxl-storage busybox:latest

	# start grafana-xxl
	docker run \
	  -d \
	  -p 3000:80 \
	  --name grafana-xxl \
	  --volumes-from grafana-xxl-storage \
	  monitoringartist/grafana-xxl:latest
}

if ! docker_installed; then
	install_docker
fi

if ! docker_running; then
	start_docker
	
	if docker_running
	then
		echo "Docker installed and started now, enjoy!"
	else
		echo "failed to start docker"
		exit 1
	fi
fi

install_grafana
run_grafana
